<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-page-header @back="goBack" content="定位器详情">
        <template slot="content">
          <span class="page-title">定位器详情</span>
          <el-tag v-if="locatorData" :type="getStatusType(locatorData.deviceStatus)" style="margin-left: 10px;">
            {{ getStatusText(locatorData.deviceStatus) }}
          </el-tag>
        </template>
      </el-page-header>
    </div>

    <div v-if="locatorData" class="detail-container">
      <!-- 第一行：设备基本信息和状态信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="12">
          <el-card class="info-card">
            <div slot="header" class="card-header">
              <span>设备基本信息</span>
              <el-button 
                style="float: right; padding: 3px 0" 
                type="text" 
                icon="el-icon-edit"
                @click="handleEdit"
                v-hasPermi="['locator:edit']"
              >编辑</el-button>
            </div>
            <div class="info-content">
              <div class="info-row">
                <span class="info-label">IMEI号码：</span>
                <span class="info-value">{{ locatorData.imei }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">设备名称：</span>
                <span class="info-value">{{ locatorData.deviceName }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">设备型号：</span>
                <span class="info-value">{{ locatorData.deviceModel }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">创建时间：</span>
                <span class="info-value">{{ parseTime(locatorData.createTime) }}</span>
              </div>
              <div class="info-row" v-if="locatorData.remark">
                <span class="info-label">备注：</span>
                <span class="info-value">{{ locatorData.remark }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="info-card">
            <div slot="header" class="card-header">
              <span>设备状态信息</span>
              <el-button 
                style="float: right; padding: 3px 0" 
                type="text" 
                icon="el-icon-refresh"
                @click="refreshStatus"
              >刷新</el-button>
            </div>
            <div class="info-content">
              <div class="info-row">
                <span class="info-label">设备状态：</span>
                <dict-tag :options="dict.type.device_status" :value="locatorData.deviceStatus"/>
              </div>

              <div class="info-row">
                <span class="info-label">电池电量：</span>
                <el-progress 
                  :percentage="locatorData.batteryLevel" 
                  :color="getBatteryColor(locatorData.batteryLevel)"
                  style="width: 200px;"
                ></el-progress>
                <span style="margin-left: 10px;">{{ locatorData.batteryLevel }}%</span>
              </div>
              <div class="info-row">
                <span class="info-label">信号强度：</span>
                <span class="info-value">{{ locatorData.signalStrength }} dBm</span>
              </div>
              <div class="info-row">
                <span class="info-label">最后上报：</span>
                <span class="info-value">{{ parseTime(locatorData.lastReportTime) }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第二行：当前位置信息和运单绑定信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="12">
          <el-card class="info-card">
            <div slot="header" class="card-header">
              <span>当前位置信息</span>
            </div>
            <div class="info-content" v-if="locatorData.currentLongitude && locatorData.currentLatitude">
              <div class="info-row">
                <span class="info-label">经度：</span>
                <span class="info-value">{{ locatorData.currentLongitude }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">纬度：</span>
                <span class="info-value">{{ locatorData.currentLatitude }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">详细地址：</span>
                <span class="info-value">{{ locatorData.currentAddress || '地址解析中...' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">定位时间：</span>
                <span class="info-value">{{ parseTime(locatorData.lastReportTime) }}</span>
              </div>
            </div>
            <div class="info-content" v-else>
              <el-empty description="暂无位置信息" :image-size="80"></el-empty>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="info-card">
            <div slot="header" class="card-header">
              <span>运单绑定信息</span>
              <el-button 
                v-if="locatorData.currentShipmentId"
                style="float: right; padding: 3px 0" 
                type="text" 
                @click="handleUnbind"
                v-hasPermi="['locator:unbind']"
              >解绑运单</el-button>
            </div>
            <div class="info-content" v-if="locatorData.currentShipmentId">
              <div class="info-row">
                <span class="info-label">运单编号：</span>
                <span class="info-value">
                  <el-link type="primary" @click="viewShipment(locatorData.currentShipmentId)">
                    {{ locatorData.currentShipmentCode }}
                  </el-link>
                </span>
              </div>
              <div class="info-row">
                <span class="info-label">绑定时间：</span>
                <span class="info-value">{{ parseTime(locatorData.bindTime) }}</span>
              </div>
            </div>
            <div class="info-content" v-else>
              <el-empty description="未绑定运单" :image-size="80"></el-empty>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第三行：地图展示 -->
      <el-row style="margin-bottom: 20px;" v-if="locatorData.currentLongitude && locatorData.currentLatitude">
        <el-col :span="24">
          <el-card class="map-card">
            <div slot="header" class="card-header">
              <span>位置地图</span>
              <div style="float: right;">
                <el-button-group>
                  <el-button size="mini" @click="mapMode = 'current'" :type="mapMode === 'current' ? 'primary' : ''">当前位置</el-button>
                  <el-button size="mini" @click="mapMode = 'track'" :type="mapMode === 'track' ? 'primary' : ''">历史轨迹</el-button>
                </el-button-group>
              </div>
            </div>
            <div class="map-container">
              <!-- 这里应该集成地图组件，如高德地图或百度地图 -->
              <div class="map-placeholder">
                <i class="el-icon-location" style="font-size: 48px; color: #409EFF;"></i>
                <p>地图组件占位</p>
                <p v-if="mapMode === 'current'">当前位置：{{ locatorData.currentAddress }}</p>
                <p v-else>历史轨迹展示</p>
                <p>经纬度：{{ locatorData.currentLongitude }}, {{ locatorData.currentLatitude }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第四行：定位日志 -->
      <el-row>
        <el-col :span="24">
          <el-card class="log-card">
            <div slot="header" class="card-header">
              <span>定位日志</span>
              <div style="float: right;">
                <el-date-picker
                  v-model="logDateRange"
                  type="datetimerange"
                  size="mini"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="handleLogDateChange"
                  style="margin-right: 10px;"
                >
                </el-date-picker>
                <el-button size="mini" icon="el-icon-refresh" @click="loadLocationLogs">刷新</el-button>
              </div>
            </div>
            <div class="log-content">
              <el-table 
                v-loading="logLoading" 
                :data="locationLogs" 
                style="width: 100%"
                max-height="400"
              >
                <el-table-column prop="locationTime" label="定位时间" width="160" sortable>
                  <template slot-scope="scope">
                    {{ parseTime(scope.row.locationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                  </template>
                </el-table-column>
                <el-table-column prop="longitude" label="经度" width="120" />
                <el-table-column prop="latitude" label="纬度" width="120" />
                <el-table-column prop="address" label="地址" show-overflow-tooltip min-width="200" />
                <el-table-column prop="speed" label="速度" width="80" sortable>
                  <template slot-scope="scope">
                    {{ scope.row.speed }} km/h
                  </template>
                </el-table-column>
                <el-table-column prop="direction" label="方向" width="80">
                  <template slot-scope="scope">
                    {{ scope.row.direction }}°
                  </template>
                </el-table-column>
                <el-table-column prop="batteryLevel" label="电量" width="80" sortable>
                  <template slot-scope="scope">
                    <el-progress 
                      :percentage="scope.row.batteryLevel" 
                      :color="getBatteryColor(scope.row.batteryLevel)"
                      :show-text="false"
                      :stroke-width="6"
                    ></el-progress>
                    <span style="margin-left: 5px; font-size: 12px;">{{ scope.row.batteryLevel }}%</span>
                  </template>
                </el-table-column>
                <el-table-column prop="signalStrength" label="信号" width="80" sortable>
                  <template slot-scope="scope">
                    {{ scope.row.signalStrength }} dBm
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="viewLogDetail(scope.row)">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 分页组件 -->
              <pagination
                v-show="logTotal > 0"
                :total="logTotal"
                :page.sync="logQueryParams.pageNum"
                :limit.sync="logQueryParams.pageSize"
                @pagination="loadLocationLogs"
                style="margin-top: 20px;"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 编辑定位器对话框 -->
    <el-dialog :title="editTitle" :visible.sync="editOpen" width="600px" append-to-body>
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="IMEI号码" prop="imei">
              <el-input v-model="editForm.imei" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="editForm.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceModel">
              <el-input v-model="editForm.deviceModel" placeholder="请输入设备型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="deviceStatus">
              <el-select v-model="editForm.deviceStatus" placeholder="请选择设备状态">
                <el-option label="正常" value="1" />
                <el-option label="离线" value="2" />
                <el-option label="故障" value="3" />
                <el-option label="维修中" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上报间隔" prop="reportInterval">
              <el-input-number v-model="editForm.reportInterval" :min="10" :max="3600" placeholder="上报间隔(秒)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="低电量阈值" prop="lowBatteryThreshold">
              <el-input-number v-model="editForm.lowBatteryThreshold" :min="0" :max="100" placeholder="低电量阈值(%)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
        <el-button @click="editOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 定位日志详情对话框 -->
    <el-dialog title="定位日志详情" :visible.sync="logDetailOpen" width="800px" append-to-body>
      <div v-if="logDetailData" class="log-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <h4>位置信息</h4>
            <div class="detail-item">
              <span class="detail-label">定位时间：</span>
              <span class="detail-value">{{ parseTime(logDetailData.locationTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">经度：</span>
              <span class="detail-value">{{ logDetailData.longitude }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">纬度：</span>
              <span class="detail-value">{{ logDetailData.latitude }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">定位精度：</span>
              <span class="detail-value">{{ logDetailData.accuracy }} 米</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">海拔高度：</span>
              <span class="detail-value">{{ logDetailData.altitude }} 米</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">移动速度：</span>
              <span class="detail-value">{{ logDetailData.speed }} km/h</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">移动方向：</span>
              <span class="detail-value">{{ logDetailData.direction }}°</span>
            </div>
          </el-col>
          <el-col :span="12">
            <h4>设备状态</h4>
            <div class="detail-item">
              <span class="detail-label">电池电量：</span>
              <span class="detail-value">{{ logDetailData.batteryLevel }}%</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">信号强度：</span>
              <span class="detail-value">{{ logDetailData.signalStrength }} dBm</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">环境温度：</span>
              <span class="detail-value">{{ logDetailData.temperature }}°C</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">环境湿度：</span>
              <span class="detail-value">{{ logDetailData.humidity }}%</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">倾斜角度：</span>
              <span class="detail-value">{{ logDetailData.tiltAngle }}°</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">接收时间：</span>
              <span class="detail-value">{{ parseTime(logDetailData.receiveTime) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <h4>地址信息</h4>
            <div class="detail-item">
              <span class="detail-label">省份：</span>
              <span class="detail-value">{{ logDetailData.province }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">城市：</span>
              <span class="detail-value">{{ logDetailData.city }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">区县：</span>
              <span class="detail-value">{{ logDetailData.district }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">详细地址：</span>
              <span class="detail-value">{{ logDetailData.address }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLocator, updateLocator, unbindShipment, getLocationLogs, getLocationLogDetail } from "@/api/locator/locator";

export default {
  name: "LocatorDetail",
  dicts: ['device_status', 'usage_status'],
  data() {
    return {
      // 定位器数据
      locatorData: null,
      // 地图模式
      mapMode: 'current',
      // 定位日志数据
      locationLogs: [],
      // 日志加载状态
      logLoading: false,
      // 日志总数
      logTotal: 0,
      // 日志查询参数
      logQueryParams: {
        pageNum: 1,
        pageSize: 10,
        locatorId: null,
        beginTime: null,
        endTime: null
      },
      // 日志日期范围
      logDateRange: [],
      // 编辑对话框
      editOpen: false,
      editTitle: "编辑定位器",
      editForm: {},
      editRules: {
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        deviceModel: [
          { required: true, message: "设备型号不能为空", trigger: "blur" }
        ],
        deviceStatus: [
          { required: true, message: "设备状态不能为空", trigger: "change" }
        ],
        reportInterval: [
          { required: true, message: "上报间隔不能为空", trigger: "blur" }
        ],
        lowBatteryThreshold: [
          { required: true, message: "低电量阈值不能为空", trigger: "blur" }
        ]
      },
      // 日志详情对话框
      logDetailOpen: false,
      logDetailData: null
    };
  },
  created() {
    const locatorId = this.$route.query.locatorId;
    if (locatorId) {
      this.loadLocatorDetail(locatorId);
      this.logQueryParams.locatorId = locatorId;
      this.loadLocationLogs();
    } else {
      this.$message.error('缺少定位器ID参数');
      this.goBack();
    }
  },
  methods: {
    /** 加载定位器详情 */
    loadLocatorDetail(locatorId) {
      getLocator(locatorId).then(response => {
        this.locatorData = response.data;
      }).catch(() => {
        this.$message.error('加载定位器详情失败');
        this.goBack();
      });
    },
    /** 加载定位日志 */
    loadLocationLogs() {
      this.logLoading = true;
      // 处理日期范围
      if (this.logDateRange && this.logDateRange.length === 2) {
        this.logQueryParams.beginTime = this.logDateRange[0];
        this.logQueryParams.endTime = this.logDateRange[1];
      } else {
        this.logQueryParams.beginTime = null;
        this.logQueryParams.endTime = null;
      }
      
      getLocationLogs(this.logQueryParams).then(response => {
        this.locationLogs = response.rows || [];
        this.logTotal = response.total || 0;
        this.logLoading = false;
      }).catch(() => {
        this.logLoading = false;
      });
    },
    /** 日期范围变化处理 */
    handleLogDateChange() {
      this.logQueryParams.pageNum = 1;
      this.loadLocationLogs();
    },
    /** 查看日志详情 */
    viewLogDetail(row) {
      getLocationLogDetail(row.logId).then(response => {
        this.logDetailData = response.data;
        this.logDetailOpen = true;
      });
    },
    /** 返回上一页 */
    goBack() {
      this.$router.go(-1);
    },
    /** 刷新状态 */
    refreshStatus() {
      this.loadLocatorDetail(this.locatorData.locatorId);
    },
    /** 编辑定位器 */
    handleEdit() {
      this.editForm = { ...this.locatorData };
      this.editOpen = true;
    },
    /** 提交编辑表单 */
    submitEditForm() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          updateLocator(this.editForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.editOpen = false;
            this.loadLocatorDetail(this.editForm.locatorId);
          });
        }
      });
    },
    /** 解绑运单 */
    handleUnbind() {
      this.$modal.confirm('是否确认解绑该定位器的运单？').then(() => {
        return unbindShipment(this.locatorData.locatorId);
      }).then(() => {
        this.$modal.msgSuccess("解绑成功");
        this.loadLocatorDetail(this.locatorData.locatorId);
      }).catch(() => {});
    },
    /** 查看运单 */
    viewShipment(shipmentId) {
      // 跳转到运单详情页面
      this.$router.push({
        path: '/logistics/shipment/detail',
        query: { shipmentId: shipmentId }
      });
    },
    /** 获取状态类型 */
    getStatusType(status) {
      const statusMap = {
        '1': 'success',
        '2': 'warning',
        '3': 'danger',
        '4': 'info'
      };
      return statusMap[status] || 'info';
    },
    /** 获取状态文本 */
    getStatusText(status) {
      const statusMap = {
        '1': '正常',
        '2': '离线',
        '3': '故障',
        '4': '维修中'
      };
      return statusMap[status] || '未知';
    },
    /** 获取电池颜色 */
    getBatteryColor(level) {
      if (level > 50) return '#67c23a';
      if (level > 20) return '#e6a23c';
      return '#f56c6c';
    }
  }
};
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
}

.detail-container {
  padding: 0;
}

.info-card, .map-card, .log-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-content {
  padding: 10px 0;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.info-label {
  font-weight: bold;
  color: #606266;
  width: 100px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  flex: 1;
}

.map-container {
  height: 400px;
  position: relative;
}

.map-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  color: #909399;
}

.log-content {
  padding: 0;
}

.log-detail {
  padding: 20px;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  width: 100px;
  flex-shrink: 0;
}

.detail-value {
  color: #303133;
  flex: 1;
}

.log-detail h4 {
  color: #303133;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-row, .detail-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-label, .detail-label {
    width: auto;
    margin-bottom: 5px;
  }
  
  .map-container {
    height: 300px;
  }
}
</style>